<template>
  <el-dialog v-model="drawer" :title="isEdit ? '编辑活动' : '新建活动'" :append-to-body="true" width="670px" custom-class="activeCreate" @close="close">
    <el-form :model="form" :rules="rules" size="small" ref="ruleRefForm" label-width="110px">
        <el-row :gutter="24" justify="space-between">
            <el-col :span="12">
                <el-form-item label="活动主题简称" prop="shortName">
                    <el-input v-model="form.shortName" placeholder="请输入" style="width:205px"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="活动主题" prop="name">
                    <el-input v-model="form.name" placeholder="请输入" style="width:205px"></el-input>
                </el-form-item>
            </el-col>
            <!-- <el-form-item label="创建时间" prop="creatTime">
                <el-date-picker v-if="!isEdit" v-model="form.createTime" type="datetime" placeholder="请选择" style="width:200px" />
                <span v-else>{{form.createTime}}</span>
            </el-form-item> -->
        </el-row>
        <el-row style="margin-top: 20px;">
            <el-form-item label="活动类型" prop="parentClassify">
                <el-select v-model="form.oneActivityId" placeholder="请选择" size="small" @change="handleActive" style="width:205px">
                    <el-option
                        v-for="item in oneTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item prop="classify" label-width="10px">
                <el-select v-model="form.twoActivityId" placeholder="请选择" size="small"  @change="twoTypeName" style="width:200px">
                    <el-option
                        v-for="item in twoTypeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
                <el-icon @click="handleSettingClassify" style="margin-left:5px;font-size:16px;--color: var(--next-bg-topBarColor);cursor:pointer;"><ele-Setting /></el-icon>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item prop="duration" label="活动期间">
                <el-date-picker
                    v-model="form.duration"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="small"
                    style="width:200px"
                />
            </el-form-item>
            <el-form-item prop="address" label="活动地点">
                <el-input v-model="form.address" placeholder="请输入" style="width:200px"></el-input>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-col :span="12">
                <el-form-item prop="productNames" label="促销产品信息">
                    <el-input v-model="form.productNames" placeholder="请输入" style="width:205px"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item prop="slogan" label="广告宣传标语">
                    <el-input v-model="form.slogan" placeholder="请输入" style="width:200px"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row style="margin-top: 20px;" justify="space-between">
            <el-form-item prop="month" label="投放月份">
                <el-date-picker
                    v-model="form.month"
                    value-format="MM"
                    type="month"
                    placeholder="请选择"
                    style="width:205px"
                />
            </el-form-item>
            <el-form-item v-show="false" prop="scene" label="投放场景">
                <el-input v-model="form.scene" placeholder="请输入" style="width:200px"></el-input>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item prop="dutyUserId" label="活动负责人">
                <el-select v-if="!isEdit" v-model="form.dutyUserId" placeholder="请选择" @change="selectDuty" size="small" style="width:205px">
                    <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickname"
                        :value="item.userId"
                    />
                </el-select>
                <span v-else>{{form.dutyUserName}}</span>
            </el-form-item>
            <el-form-item prop="stage" label="活动阶段">
                <el-select v-model="form.stageId" placeholder="请选择" @change="selectStage" size="small" style="width:200px">
                    <el-option
                        v-for="item in stageList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
        </el-row>
        <el-form-item style="margin-top: 20px;" prop="description" label="活动描述">
            <el-input type="textarea" v-model="form.description" placeholder="请输入" style="width: 515px"></el-input>
        </el-form-item>
        <el-row justify="space-between">
            <el-form-item label="服务商" prop="service">
                <el-select v-model="form.service" placeholder="请选择" @change="selectService" size="small" filterable>
                    <el-option
                        v-for="item in serviceList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-show="false" label="服务商对接人" prop="serviceManage" label-width="95px">
                <el-select v-model="form.serviceManage" placeholder="请选择" size="small">
                    <el-option
                        v-for="item in activeManageList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-show="false" label="联系电话" prop="phone" label-width="70px">
                <el-input v-model="form.phone" placeholder="请输入" style="width:135px"></el-input>
            </el-form-item>
        </el-row>
        <el-row justify="space-between">
            <el-form-item label="活动预算(元)" prop="budgetMoney">
                <el-input v-model="form.budgetMoney" placeholder="请输入" style="width:205px"></el-input>
            </el-form-item>
            <el-form-item v-show="false" label="支付方式" prop="payType">
                <el-select v-model="form.payType" placeholder="请选择" size="small" style="width:200px">
                    <el-option
                        v-for="item in payTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
        </el-row>
        <el-form-item label="备注" prop="remark">
            <el-input type="textarea" placeholder="请输入" v-model="form.remark" style="width: 515px"></el-input>
        </el-form-item>
        <el-divider />
        <Document style="margin-left: 30px;" v-if="drawer" :code="code" :relevance-id="form.id" :relevance-name="form.shortName" v-model:resultList="resultList" :limit="9" ></Document>
    </el-form>
    <template #footer>
        <el-row justify="center">
            <el-button size="small" type="primary" @click="submitForm(ruleRefForm)">提交</el-button>
            <el-button size="small" type="default" @click="cancelForm(ruleRefForm)">取消</el-button>
        </el-row>
    </template>
    <active-classify v-model:dialogDrawer="dialogClassify" @onClose="activeClose"></active-classify>
  </el-dialog>
</template>

<script>
import { computed, onMounted, reactive, ref, toRefs, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ActiveClassify from './ActiveClassify.vue'
import { Session } from '/@/utils/storage'
import Document from '/@/components/document/index.vue'
import api from '/@/api/commonApi'

export default {
    name: 'ActiveCreate',
    props: {
        dialogDrawer: {
            props: Boolean,
            default: false
        },
        isEdit: {
            props: Boolean,
            default: false
        },
        editForm: {
            props: Object,
            default: () => {
                return {}
            }
        }
    },
    components: {
        ActiveClassify,
        Document
    },
    emits: ['onSubmit', 'update:dialogDrawer'],
    setup(props, context){
        const { dialogDrawer, editForm, isEdit } = toRefs(props)
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        const ruleRefForm = ref()
        const uploadBanner = ref()
        const state = reactive({
            code: 'MARKET',
            oneTypeList: [],
            twoTypeList: [],
            serviceList: [],
            userList: [],
            resultList: [],
            form: {
                id: null,
                shortName: '', // 简称
                name: '', // 名称
                oneActivityId: '', // 一级分类id
                oneActivityName: '',
                twoActivityId: '', // 二级分类
                twoActivityName: '',
                dutyUserId: '', // 负责人id
                dutyUserName: '',
                startTime: '', // 开始时间
                endTime: '', // 结束时间
                duration: '', // 活动期间
                address: '', // 活动地点
                productNames: '', // 促销产品信息
                slogan: '', // 广告语
                month: null, // 月份
                stageId: '', // 阶段id
                stageName: '',
                stageListSort: 0,
                description: '', // 活动描述
                remark: '', // 备注
                budgetMoney: 0, // 预算资金
                accessoryUrl: '', // 附件地址
                documentUrl: '', // 文件地址
                supplierList: [], // 选择的供应商

                payType: '', // 隐藏列
                serviceManage: '',
                phone: '',
                scene: '',
                accessoryList: [], // 上传的附件
                fileList:[], // 上传的文件
            },
            rules: {
                shortName: [{ required: true, message: '请输入活动主题简称', trigger: 'blur' }],
                name: [{ required: true, message: '请输入活动主题', trigger: 'blur' }]
            },
            parentClassifyList: [],
            parentIndex: 0,
            stageList: [],
            activeManageList: [],
            payTypeList: [],
            dialogClassify: false
        })
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        const handleActive = e => {
            getActivityType(state.form.oneActivityId)
            state.form.twoActivityId = ''
            let list = JSON.parse(JSON.stringify(state.oneTypeList))
            const result = list.find(item => {
                return item.id == e
            })
            state.form.oneActivityId = result.id
            state.form.oneActivityName = result.name
        }
        const submitForm = formEl => {
            if (!formEl) return
            formEl.validate(valid => {
                if (valid) {
                    close()
                    if(isEdit.value){
                        ElMessage.success('编辑成功')
                    }else{
                        state.form.startTime = state.form.duration[0]
                        state.form.endTime = state.form.duration[1]
                        api.addMarketActivity(state.form).then(res => {
                            ElMessage.success('新建成功')
                            if (res.data && res.data.id) {
                              state.resultList.forEach(file => {
                                file.relevanceId = res.data.id
                                file.relevanceName = res.data.shortName
                              })
                            }
                            reset()
                            api.fileRelevanceModule(state.resultList)
                            context.emit('onSubmit', true)
                        })
                    }
                }
            })
        }
        const cancelForm = formEl => {
            if (!formEl) return
            formEl.resetFields()
            context.emit('update:dialogDrawer', false)
        }
        watch(() => dialogDrawer.value,
            val => {
                if(val) {
                    getActivityType("0")
                    supplierList()
                    getStageList()
                    getEnterpriseUsers()
                    if (ruleRefForm.value) {
                        ruleRefForm.value.resetFields()
                    }
                    if(isEdit.value){
                        // 编辑状态
                        state.form = editForm.value
                    }
                }
            }
        )
        // 重置
        const reset = () => {
            state.form = {
                shortName: '', // 简称
                name: '', // 名称
                oneActivityId: '', // 一级分类id
                oneActivityName: '',
                twoActivityId: '', // 二级分类
                twoActivityName: '',
                dutyUserId: '', // 负责人id
                dutyUserName: '',
                startTime: '', // 开始时间
                endTime: '', // 结束时间
                duration: '', // 活动期间
                address: '', // 活动地点
                productNames: '', // 促销产品信息
                slogan: '', // 广告语
                month: null, // 月份
                stageId: '', // 阶段id
                stageName: '',
                stageListSort: 0,
                description: '', // 活动描述
                remark: '', // 备注
                budgetMoney: 0, // 预算资金
                accessoryUrl: '', // 附件地址
                documentUrl: '', // 文件地址
                supplierList: [], // 选择的供应商

                payType: '', // 隐藏列
                serviceManage: '',
                phone: '',
                scene: '',
                accessoryList: [], // 上传的附件
                fileList:[], // 上传的文件
            }
        }
        // 活动类型设置
        const handleSettingClassify = () => {
            state.dialogClassify = true
        }
        // 获取活动类型
        const getActivityType = (leaderId) => {
            api.getActivityType({leaderId: leaderId}).then(res => {
                if (leaderId != '0') {
                    state.twoTypeList = res.data
                }else{
                    state.oneTypeList = res.data
                }
            })
        }
        // 获取供应商列表
        const supplierList = () => {
            api.supplierList({
                current: 1,
                size: 1000
            }).then(res => {
                state.serviceList = res.data.records
            })
        }
        // 关闭活动类型设置页面
        const activeClose = () => {
            state.oneTypeList = []
            state.twoTypeList = []
            getActivityType("0")
        }
        // 二级分类名称
        const twoTypeName = e => {
            let list = JSON.parse(JSON.stringify(state.twoTypeList))
            const result = list.find(item => {
                return item.id == e
            })
            state.form.twoActivityName = result.name
        }
        // 选择供应商
        const selectService = e => {
            let list = JSON.parse(JSON.stringify(state.serviceList))
            const result = list.find(item => {
                return item.id == e
            })
            state.form.supplierList = [result]
        }
        // 获取企业人员列表
        const getEnterpriseUsers = () => {
            api.getEnterpriseUsers().then(res => {
                state.userList = res.data
            })
        }
        // 选择负责人
        const selectDuty = e => {
            let list = JSON.parse(JSON.stringify(state.userList))
            const result = list.find(item => {
                return item.userId == e
            })
            state.form.dutyUserId = result.userId
            state.form.dutyUserName = result.nickname
        }
        // 获取活动阶段
        const getStageList = () => {
            api.stageList({status: 1, type: 1}).then(res => {
                state.stageList = JSON.parse(JSON.stringify(res.data))
            })
        }
        // 选择活动阶段
        const selectStage = (e) => {
            let list = JSON.parse(JSON.stringify(state.stageList))
            const result = list.find(item => {
                return item.id == e
            })
            state.form.stageId = result.id
            state.form.stageName = result.name
            state.form.stageListSort = result.sort
        }
        // 附件上传
        const accessoryOnSuccess = (response, uploadFiles) => {
            state.form.accessoryUrl = response.data.src
        }
        // 文件上传
        const fileOnSuccess = (response, uploadFiles) => {
            state.form.documentUrl = response.data.src
        }
        // 文件删除
        const handleRemove = file => {
            uploadBanner.value.handleRemove(file)
        }
        return {
            ...toRefs(state),
            drawer,
            twoTypeName,
            handleActive,
            ruleRefForm,
            submitForm,
            close,
            reset,
            selectDuty,
            cancelForm,
            selectStage,
            getStageList,
            supplierList,
            selectService,
            handleRemove,
            fileOnSuccess,
            accessoryOnSuccess,
            getActivityType,
            getEnterpriseUsers,
            handleSettingClassify,
            activeClose
        }
    }
}
</script>

<style lang="scss">
.activeCreate{
    .el-form-item{
        align-items: start;
        flex: 1;
    }
    .el-upload-dragger{
        padding: 5px 10px;
    }
    .el-upload{
        width: 515px;
        .el-icon{
            margin-bottom: 0;
            font-size: 42px;
            line-height: 42px;
        }
    }
}
</style>
